import Vue from 'vue'
import Vuex from 'vuex'



Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
		address: JSON.parse(uni.getStorageSync('address') || '{}')
	},
	mutations: {
		add (state,goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if (!findResult) {
				state.cart.push(goods)
			}
			else {
				console.log(findResult.goods_count)
				findResult.goods_count += 1
			}
			this.commit('GetStorage')
		},
		GetStorage (state) {
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		GetTotal (state) {
			
		},
		ChangeRario (state,goods) {
			let findResults = state.cart.find((item) => {
				if (item.goods_id === goods.goods_id) {
					return item
				}
			})
			if (findResults) {
				findResults.goods_state = !goods.goods_state
				this.commit('GetStorage')
			}
		
		},
		ChangeNumber (state,goods) {
			state.cart.forEach((item) => {
				if (item.goods_id === goods.goods_id) {
					item.goods_count = goods.goods_count
				}
			})
			this.commit('GetStorage')
		},
		ChangeShop (state,goods) {
			let index = state.cart.findIndex(item => item.goods_id === goods.goods_id)
			state.cart.splice(index,1)
			this.commit('GetStorage')
		},
		ChangeAddress (state,address) {
			state.address = address
			this.commit('ChangeAddressLoop')
		},
		ChangeAddressLoop (state) {
			uni.setStorageSync('address',JSON.stringify(state.address))
		},
		ChangeCartStatsu (state,status) {
			state.cart.forEach((item) => {
				item.goods_state = status
			})
			console.log(state.cart)
			this.commit('GetStorage')
		}
		
	},
	getters: {
		CartTotal (state) {
			let c = 0
			console.log(state)
			state.cart.forEach( (x) => {
				if (x.goods_state) {
					c += x.goods_count
				}
			})
			return c
		},
		adds(state) {
			// provinceName  cityName countyName  detailInfo
			if (!state.address.provinceName) return '' 
			return state.address.provinceName + state.address.cityName + state.address.countyName + state.address.detailInfo
		},
		changeCartTotal(state) {
			let c = 0
			console.log(state)
			state.cart.forEach( (x) => {
				if (x.goods_state) {
					c += x.goods_count
				}
			})
			return c
		},
		changeCartPrice (state) {
			let c = 0
			state.cart.forEach((item) => {
				if (item.goods_state) {
					c = c + (item.goods_count * item.goods_price)
				}
			})
			return c.toFixed(2)
		}
	}
	
})

export default store